package com.txtsqlclient.domain;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.txtsqlclient.dataaccess.database.connection.ConnectionException;

/**
 * @author spadda
 */
public enum DataSourceType {

	/** MySQL with mysql-connector driver. */
	MYSQL("M", "MySQL", "com.mysql.jdbc.Driver", "jdbc:mysql://{ip}/{database}"),

	/** Microsoft SQL Server with jTDS driver. */
	SQL_SERVER("S", "MS SQL Server", "net.sourceforge.jtds.jdbc.Driver",
			"jdbc:jtds:sqlserver://{ip}/{database}"),

	/** Sybase Server with jTDS driver. */
	SYBASE("B", "Sybase", "net.sourceforge.jtds.jdbc.Driver",
			"jdbc:jtds:sybase://{ip}/{database}"),

	/** PostgreSQL Server with open-source PostgreSQL driver. */
	POSTGRESQL("P", "PostgreSQL", "org.postgresql.Driver",
			"jdbc:postgresql://{ip}/{database}"),

	/** CSV file with CsvJdbc driver. */
	CSV("C", "CSV", "org.relique.jdbc.csv.CsvDriver", "jdbc:relique:csv:{file}");

	/** Identifier. */
	private final String identifier;

	/** Name. */
	private final String name;

	/** Class name of the Driver. */
	private final String driverClassName;

	/** URL format for the connection. */
	private final String connectionURL;

	private final static Log LOGGER = LogFactory.getLog(DataSourceType.class);

	private DataSourceType(final String identifier, final String name,
			final String driverClassName, final String connectionURL) {
		this.identifier = identifier;
		this.name = name;
		this.driverClassName = driverClassName;
		this.connectionURL = connectionURL;
	}

	public static DataSourceType resolveDataSourceType(
			final String dsTypeIdentifier) {
		DataSourceType matchedDsType = null;
		for (final DataSourceType dsType : DataSourceType.values()) {
			if (dsType.identifier.equalsIgnoreCase(dsTypeIdentifier)) {
				matchedDsType = dsType;
			}
		}
		LOGGER.debug("Resolved Data Source type: " + matchedDsType
				+ " from identifier: " + dsTypeIdentifier);
		return matchedDsType;
	}

	public String getConnectionURL(final DataSource ds) {
		return ds.formatURL(this.connectionURL);
	}

	public void loadDriverClass() throws ConnectionException {
		try {
			Class.forName(this.driverClassName);
		} catch (ClassNotFoundException e) {
			throw new ConnectionException("Could not find driver class name:"
					+ this.driverClassName, e);
		}
	}

	public String toString() {
		final StringBuffer buf = new StringBuffer();
		buf.append("[Identifier:");
		buf.append(this.identifier);
		buf.append(", Name:");
		buf.append(this.name);
		buf.append(", Driver:");
		buf.append(this.driverClassName);
		buf.append(", connectionURL:");
		buf.append(this.connectionURL);
		buf.append("]");
		return buf.toString();
	}

	/**
	 * @return the identifier
	 */
	public String getIdentifier() {
		return identifier;
	}

	/**
	 * @return the name
	 */
	public String getName() {
		return name;
	}

}
